import struct


def get_price(data, pos):
    """
    获取价格
    :param data: 原数据
    :param pos: 位置
    :return:
    """
    pos_byte = 6

    b_data = index_bytes(data, pos)
    int_data = b_data & 0x3f

    sign = True if b_data & 0x40 else False

    if b_data & 0x80:
        while b_data & 0x80:
            pos += 1
            b_data = index_bytes(data, pos)

            int_data += (b_data & 0x7f) << pos_byte
            pos_byte += 7

    pos += 1

    int_data = -int_data if sign else int_data
    return int_data, pos


def get_volume(ivol):
    """
    获取交易量
    :param ivol:
    :return:
    """
    log_point = ivol >> (8 * 3)
    hleax = (ivol >> (8 * 2)) & 0xff  # [2]
    lheax = (ivol >> 8) & 0xff  # [1]
    lleax = ivol & 0xff  # [0]

    dwEcx = log_point * 2 - 0x7f
    dwEdx = log_point * 2 - 0x86
    dwEsi = log_point * 2 - 0x8e
    dwEax = log_point * 2 - 0x96

    if dwEcx < 0:
        tmpEax = - dwEcx
    else:
        tmpEax = dwEcx

    dbl_xmm6 = pow(2.0, tmpEax)

    if dwEcx < 0:
        dbl_xmm6 = 1.0 / dbl_xmm6

    if hleax > 0x80:
        dwtmpeax = dwEdx + 1
        tmpdbl_xmm3 = pow(2.0, dwtmpeax)

        dbl_xmm0 = pow(2.0, dwEdx) * 128.0
        dbl_xmm0 += (hleax & 0x7f) * tmpdbl_xmm3
        dbl_xmm4 = dbl_xmm0

    else:
        if dwEdx >= 0:
            dbl_xmm0 = pow(2.0, dwEdx) * hleax
        else:
            dbl_xmm0 = (1 / pow(2.0, dwEdx)) * hleax

        dbl_xmm4 = dbl_xmm0

    dbl_xmm3 = pow(2.0, dwEsi) * lheax
    dbl_xmm1 = pow(2.0, dwEax) * lleax

    if hleax & 0x80:
        dbl_xmm3 *= 2.0
        dbl_xmm1 *= 2.0

    dbl_ret = dbl_xmm6 + dbl_xmm4 + dbl_xmm3 + dbl_xmm1

    return dbl_ret


def get_datetime(category, buffer, pos):
    """
    获取时间格式
    :param category:
    :param buffer:
    :param pos:
    :return:
    """
    hour = 15
    minute = 0

    if category < 4 or category == 7 or category == 8:
        (zipday, tminutes) = struct.unpack('<HH', buffer[pos: pos + 4])
        year = (zipday >> 11) + 2004
        month = int((zipday % 2048) / 100)
        day = (zipday % 2048) % 100

        hour = int(tminutes / 60)
        minute = tminutes % 60
    else:
        (zipday,) = struct.unpack('<I', buffer[pos: pos + 4])

        year = int(zipday / 10000)
        month = int((zipday % 10000) / 100)
        day = zipday % 100

    pos += 4

    return year, month, day, hour, minute, pos


def get_time(buffer, pos):
    """

    :param buffer:
    :param pos:
    :return:
    """
    (tminutes,) = struct.unpack('<H', buffer[pos: pos + 2])

    hour = int(tminutes / 60)
    minute = tminutes % 60

    pos += 2

    return hour, minute, pos


def index_bytes(data, pos):
    """

    :param data:
    :param pos:
    :return:
    """
    return data[pos]
